// Copyright 2010 The Go Example Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"fmt"
	"os"
	"archive/tar"
	"io"
)

func main() {
	fileName := "data/data.tar"
	//Open File
	file, err := os.Open(fileName, os.O_CREATE, 0)
	if file == nil {
		fmt.Printf("can't create file;err=%s\n", err.String())
		os.Exit(1)
	}
	//Close File
	defer file.Close()
	// create tar.Writer
	tw := tar.NewWriter(file)
	//Close tar.Writer
	defer tw.Close()

	//need to archive file
	f, e := os.Open("data/data.txt", 0444, 0)

	defer f.Close()
	if f == nil {
		fmt.Printf("Can't Open file.err=%s\n", e.String())
		os.Exit(1)
	}
	//get f FileInfo
	fi, err2 := f.Stat()
	if err2 != nil {
		os.Exit(1)
	}

	hdr := new(tar.Header)

	hdr.Size = fi.Size
	hdr.Name = fi.Name
	hdr.Mode = int64(fi.Mode)
	hdr.Typeflag = 0
	//witer file header info to tar archive
	if err := tw.WriteHeader(hdr); err != nil {
		fmt.Println("WriterHeard cause err.")
	}
	//var data bytes.Buffer
	// Write file data to Tar archive
	io.Copy(tw, f)
}
